<template>
	<div>
		<head-top></head-top>
		<div class="boxWrap">			
			<div class="alert alert-danger text-center" v-if="beforeUploadError" style="background-color: #f2dede;">
				<a href="#" class="close" data-dismiss="alert">&times;</a>
				<strong>{{beforeUploadTip}}！</strong>
			</div>
			<div class="upload_wrap">	
				<div class="upload_con">
					<img src="../../assets/img/addData.png" alt="uploadImg" style="width:224px;height:240px;margin:30px 0;"/>
					<div id="fileSpan" class="text-center" @dragenter="dragenterSpan()" @dragover='dragoverSpan($event)'  @dragleave="dragleaveSpan()" 
						@drop='dropSpan($event)' style="width:300px;height:150px;margin:0 auto;border:2px dashed #ccc;">
						<h4 style="margin-top:30px;line-height:20px;">点击浏览本地文件上传数据</br>或直接将文件拖至此处</h4>
						<p>文件大小 < 10M</p>
						<p>您的剩余空间：{{remained_storage}}M</p>
					</div>
					<a href="javascript:;" class="file">浏览本地文件
						<input type="file" multiple id="uploadInput" @change="changeInput()" accept=".xlsx, .xls, .csv, .tsv" ref="file"/>
					</a>
				</div>			
			</div>					
		</div>
		<footerHtml></footerHtml>
		<!--遮罩层和loading-->
		<div id="mask" v-show="seen" :style="{height: relHeight}"></div>
		<img src="../../assets/img/loading.gif" alt="loading" class="loading_img" v-if="loading"/>
		<!--end-->
		<div class="bomb_box upload_bomb" v-show="seenEdit" :class="{'bomb_box_tip':bombTip}">
			<p class="data_info_tip" v-if="seen_tip">{{uploadTip}}</p>
			<p class="uploadName text-left" style="color: rgba(26,44,74,0.20);">{{uploadName}}({{fileSizeFix}}KB)</p>
			<p class="text-left">
				<span class="data_info_name" style="margin-right:14px;">数据名称</span>
				<input type="text" class="data_info_name_val" v-model="uploadTitle"/>
			</p>			
			<p class="text-left">
				<span class="data_info_name" style="display: block; float: left;">数据描述</span>
				<textarea name="des" class="data_info_des_val" v-model="uploadDes"></textarea>
			</p>
			<p class="text-left ">
				<span class="data_info_name" style="margin-right:36px;">隐私性</span>	
				<!--上传数据公开私有去掉了 v-on:click="changeClassFun(index)"-->
				<span v-for='(data,key,index) in visibleTypes'  v-bind:class='{change_visible:index==addClassIndex}' class="data_info_visible change_visible">{{data.data}}</span>
			</p>
			<p class="text-left">
				<span class="data_info_name">包含标题</span>
				<label class="input_label_beautify">				
			        <input class="input_checkbox" type="checkbox" name="data_checkbox" v-model="checkHeader" @change="changeHeader()">
			        <span class="input_checkboxInput"></span>
				</label>
			</p>
			<p class="text-left" v-show="dataPrice">
				<span class="data_info_name">数据定价</span>
				<input type="number" class="data_info_pai_val" v-model="uploadPrice"/>
				<span>Atom</span>
			</p>
			<p class="text-left" style="margin-left:94px;" v-show="dataPrice">
				<label class="input_label_beautify">				
			        <input class="input_radio" type="checkbox" name="agree_checkbox" @change="agreeAgreement()" v-model="checkAgree">
			        <span class="input_checkbox input_radioInput"></span>我已同意数据共享协议
				</label>				
			</p>
			<p  class="text-right">
				<button class="data_info_cancel btn" @click="bombBoxHide()">取消</button>
				<button class="data_info_sure btn" @click="upload()">确定上传</button>
			</p>
		</div>
	</div>
	
</template>

<script>
	//引入公共模块
	import headTop from '@/components/headTop'
	import footerHtml from '@/components/footerHtml'
	import global_ from '@/components/global'
	import {urlGetUserInfo} from '../../api/api'
	
export default {
    name: 'uploadData',   
    data(){
    	return {
    		token:localStorage.getItem('token'),
    		username:localStorage.getItem('username'),
    		uploadTip:'请填写完整信息!',
    		seen:false,
    		loading:false,
    		relHeight:'',
    		seen_tip:false,
    		seenEdit:false,
    		beforeUploadError:false,
    		beforeUploadTip:'',
    		uploadName:'',
    		uploadTitle:'',
    		uploadStart:'',
    		uploadDes:'',
    		uploadVis:1,
    		agreementVal:0,
    		addClassIndex:1,
    		uploadPrice:'',
    		fileObj:'',
    		fileSize:'',
    		fileSizeFix:'',
    		headerVal:0,
    		checkHeader:'',
    		checkAgree:'',
			bombTip:false,
			dataPrice:false,
			fileType:['.xlsx','.csv','.xls','.tsv'],
			visibleTypes: {  
//				data1: {  
//					data: "公开"
//				},  
				data2: {  
					data: "私有"
				}
			},			
			sizeObj:[],
			remained_storage:''
    	}
    },
    components:{
    	headTop,
    	footerHtml
    },   
    mounted(){
    	let sendData={
				username:this.username
			};
			urlGetUserInfo(sendData).then(response => {
	  			if(response.data.code==200){	  				
	  				let resData=response.data.data;
	  				this.remained_storage=resData.remained_storage ;
	  				this.remained_storage=this.remained_storage.toFixed(2)
	  			}				    		
	     	}).catch(error => {
	     		if(error.response.data.code==401){
            		localStorage.clear();
            		this.$router.replace('/login');
				}
	      	});
    },
    methods: { 
    	bombBoxHide(){
    		this.seen=false;
	    	this.seenEdit=false;
    	},
    	changeHeader(){
			if(this.checkHeader==true){
				this.headerVal=1;
			}else{
				this.headerVal=0;
			}
		},
		agreeAgreement(){
			if(this.checkAgree==true){
				this.agreementVal=1;
			}else{
				this.agreementVal=0;
			}			
		},
		changeClassFun:function(index) {  
			if(index==0){
				this.dataPrice=true;
			}else{
				this.dataPrice=false;
			}
			this.addClassIndex = index;  
			this.uploadVis=index;
		},
	    upload(){ 	    	
	    	// FormData 对象	    	
		    let form = new FormData();
	    	form.append("title", this.uploadTitle);// 可以增加表单数据
	    	form.append("description", this.uploadDes);
	    	form.append("visible",this.uploadVis);
	    	form.append("file_header", this.headerVal);
	    	form.append("price", this.uploadPrice);
	    	form.append("file", this.fileObj); // 文件对象    
	
	    	if(this.uploadTitle==''||this.uploadDes==''){
            	this.seen_tip=true;
            	this.bombTip=true;
            }else{
	            if(this.uploadVis==0){
	            	if(this.uploadPrice==''|| this.agreementVal!=1){
	            		this.seen_tip=true;
	            		this.bombTip=true;
	            		return false;
	            	}else{
	            		this.seen_tip=false;
	            		this.bombTip=false;
	            	}
	            }
            	var hashToken = "Basic " +window.btoa(this.token+':'+''),
            		self_data=this;
            	self_data.seenEdit=false;
		      	self_data.loading=true;
            　			$.ajax({
	                url:global_.urlUpload,
	                type:"post",
	                data:form,
	                processData:false,
	                contentType:false,
	                beforeSend:function(XMLHttpRequest){
                     	XMLHttpRequest.setRequestHeader("Authorization", hashToken);
                 	},
	                success:function(data){
	                	if(data.code==200){	 
	                		self_data.seen=false;
		      				self_data.loading=false;
	                		let res_data_id=data.data.data_id;
	                		localStorage.setItem('data_id',res_data_id); 
	                		self_data.$router.push({name:"dataDetails",params:{id:res_data_id,name:self_data.username}})
	                	}else{
	                		self_data.seen=true;
	                		self_data.seenEdit=true;
		      				self_data.loading=false;
	                		$('.data_info_sure').remove('disabled');
	                		self_data.seen_tip=true;
	                		self_data.uploadTip=data.message;
	                	}	                	
	                }
				});
            }
	    },	    
	    analysisList(obj){	
	    	this.fileObj = obj[0]; // 获取文件对象
    		this.fileSize =this.fileObj.size;  // 获取文件大小
    		this.uploadName= this.fileObj.name;// 获取文件文件
			let index1=this.uploadName.lastIndexOf("."),
			    index2=this.uploadName.length,
			    postf=this.uploadName.substring(index1,index2);//后缀名
			console.log(postf);
			if($.inArray(postf,this.fileType)==-1){
				this.beforeUploadError=true;
				this.beforeUploadTip='抱歉，文件格式不符合';
				return false;
			}
			//文件大于30M，就不上传
			if(this.fileSize>=10485760){
				this.beforeUploadError=true;
				this.beforeUploadTip='抱歉，文件超过了10M，不能上传';
				return false;
            }
			//把文件大小放到一个数组中，然后再去比较，如果有比较上的，就认为重复了，不能上传
			if( this.sizeObj.indexOf(this.fileSize) != -1 ){
				this.beforeUploadError=true;
				this.beforeUploadTip='已经选择，不能重复上传，请刷新页面';
				return false;
			}				
			//把这个文件的大小放进数组中
			this.sizeObj.push(this.fileSize);
			//文件上传了
			if( this.fileSize > 0 ){
    			this.seen=true;
    			this.seenEdit=true;
    			this.relHeight=`${document.documentElement.scrollHeight}px`;
			}	
			this.fileSizeFix=Number(this.fileSize/1024).toFixed(2);
		},
		dragenterSpan(){
			$(this).text("可以释放鼠标了！").css("background","#ccc");
		},
		dragoverSpan(event){
	      event.preventDefault();
	    },
		dragleaveSpan(){
			$(this).text("或者将文件拖到此处").css("background","none");
		},
		dropSpan(ev){
			ev.preventDefault();    //阻止拖放后的浏览器默认行为
  			const data = ev.dataTransfer.files;  // 获取文件对象
  			console.log(data);
			this.analysisList(data);		//解析列表函数
		},
		changeInput(){
			this.analysisList(this.$refs.file.files);
		}
	    

  	}
}
</script>


<style lang="css">
	@import "../../assets/css/base.css"
</style>
<style lang="css">
	@import "../../assets/css/upload.css"
</style>
<style lang="css">
	@import "../../assets/css/data_info.css"
</style>
